<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\admin\model\Access;
use app\common\component\Session as SessionAlias;
use think\App;

class Base extends BaseController
{


    protected $admin = [];
    protected $userId = 0;
    protected $authId = 0;
    protected $access = [];
    protected $host = '';

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->host = env('host', '');;
        $this->assign('host', $this->host);
        $this->assign('title', config('app')['title']);
        $this->assign('qqkey', config('app')['qqMapKey']);
        $noController = ['Common'];
        if (!in_array($this->request->controller(), $noController)) {
            $this->verifyLogin();
            $this->verifyAccess();
        }
    }


    protected function verifyLogin()
    {
        $login = session(SessionAlias::ADMIN_LOGIN_INFO);
        $login = object2array($login);
        if (empty($login)) {
            if (isAjax()) {
                ajaxError('请登陆', 100001);
            }
            header('location:/admin/login/index');
            exit;
        }
        $this->admin = $login;
        $this->userId = $login['id'];
        $this->authId = intval($this->admin['auth_id']);

    }

    protected function verifyAccess()
    {
        $access = session(SessionAlias::ADMIN_ACCESS);
        $lang = intval(session('lang')) ;
        if (empty($access)) {
            $access = $this->setAccess($lang);
        }
        $controller = $this->request->controller();
        $action = $this->request->action();
        $path = strtolower($controller) . '/' . strtolower($action);
        if (!in_array($path, $access)) {
            if (isAjax()) {
                ajaxError('没有权限访问', 100002);
            }
        }
    }

    protected function setAccess(): array
    {
        $access = new Access();
        $result = $access->getMyAccess($this->authId);
        $access = [];
        foreach ($result as $item) {
            if ($item['url']) {
                $access[] = strtolower($item['url']);
            }
        }
        session(SessionAlias::ADMIN_ACCESS, $access);
        return $access;
    }


}

